package com.longcai.piaojia.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.adapter.ChooseGoodsNumGridAdapter;
import com.longcai.piaojia.adapter.ChooseGoodsPriceGridAdapter;
import com.longcai.piaojia.adapter.ChooseGoodsTimeGridAdapter;
import com.longcai.piaojia.conn.ChooseGoodsListGet;
import com.longcai.piaojia.conn.ChooseGoodsNumListGet;
import com.longcai.piaojia.conn.ChooseGoodsPriceListGet;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.conn.GoodsBookGet;
import com.longcai.piaojia.dialog.RegisterDialog;
import com.longcai.piaojia.util.MyToast;
import com.longcai.piaojia.widget.NoScrollGridView;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/2.
 */
public class ChooseGoodsActivity extends BaseActivity implements View.OnClickListener {

    @BoundView(R.id.choose_goods_time_nsgv) private NoScrollGridView choose_goods_time_nsgv;
    @BoundView(R.id.choose_goods_num_nsgv) private NoScrollGridView choose_goods_num_nsgv;
    @BoundView(R.id.choose_goods_price_nsgv) private NoScrollGridView choose_goods_price_nsgv;
    private List<ChooseGoodsListGet.TimeEntity> lists_time = new ArrayList<>();
    private List<ChooseGoodsNumListGet.NumEntity> lists_num = new ArrayList<>();
    private List<ChooseGoodsPriceListGet.PriceEntity> lists_price = new ArrayList<>();
    private ChooseGoodsTimeGridAdapter chooseGoodsTimeGridAdapter;
    private ChooseGoodsNumGridAdapter chooseGoodsNumGridAdapter;
    private ChooseGoodsPriceGridAdapter chooseGoodsPriceGridAdapter;
    @BoundView(R.id.choose_goods_all_price_tv) private TextView choose_goods_all_price_tv;
    @BoundView(R.id.choose_goods_add_ll) private LinearLayout choose_goods_add_ll;
    @BoundView(R.id.choose_goods_number_tv) private TextView choose_goods_number_tv;
    @BoundView(R.id.choose_goods_minus_ll) private LinearLayout choose_goods_minus_ll;
    @BoundView(R.id.choose_goods_to_car_ll) private LinearLayout choose_goods_to_car_ll;
    @BoundView(R.id.choose_goods_bottom_all_price_tv) private TextView choose_goods_bottom_all_price_tv;
    @BoundView(R.id.choose_goods_all_price_number_tv)  private TextView choose_goods_all_price_number_tv;
    @BoundView(R.id.choose_goods_submit_tv) private TextView choose_goods_submit_tv;

    private int timeSelectPosition = -1;
    private int numSelectPosition = -1;
    private int priceSelectPosition = -1;

    private int width;

    private ChooseGoodsListGet.ChooseGoodsListEntity chooseGoodsList;

    //    private TrilateralLoginGet trilateralLoginGet = new TrilateralLoginGet(new AsyCallBack<String>(){
//
//        @Override
//        public void onSuccess(String toast, int type, String s) throws Exception {
//            super.onSuccess(toast, type, s);
//
//            Bundle bundle_web = new Bundle();
//            bundle_web.putString("title", getResources().getString(R.string.goods_info_bottom_seat_buy_text));
//            bundle_web.putString("url", "http://mseat.0368.com/local/25_8/areas.html?pid=" + goodsInfo.productid);
//
//            startActivity(new Intent(GoodsInfoActivity.this, WebActivity.class).putExtras(bundle_web));
//
////            Bundle bundle = new Bundle();
////
////            bundle.putString("goodsInfoId", goodsInfo.id);
////            bundle.putString("picurl", goodsInfo.picurl);
////            bundle.putString("place_name", goodsInfo.place_name);
////            bundle.putString("start_time", goodsInfo.start_time);
////            bundle.putString("title", goodsInfo.title);
////            bundle.putString("classid", goodsInfo.classid);
////
////            bundle.putString("is_seat", goodsInfo.is_seat);
////            bundle.putString("status", goodsInfo.status);
////
////            startActivity(new Intent(GoodsInfoActivity.this, ChooseGoodsActivity.class).putExtras(bundle));
//
//        }
//
//        @Override
//        public void onFail(String toast, int type) throws Exception {
//            super.onFail(toast, type);
//
//            Toast.makeText(GoodsInfoActivity.this, toast, Toast.LENGTH_LONG).show();
//
//        }
//    });

    // 价钱
    private ChooseGoodsPriceListGet chooseGoodsPriceListGet = new ChooseGoodsPriceListGet(new AsyCallBack<ChooseGoodsPriceListGet.ChooseGoodsPriceListEntity>() {

        @Override
        public void onSuccess(String toast, int type, ChooseGoodsPriceListGet.ChooseGoodsPriceListEntity chooseGoodsPriceListEntity) throws Exception {

            lists_price.addAll(chooseGoodsPriceListEntity.PriceEntityList);

            // 判断 list长度 如果有值就让隐藏的价格布局显示 没有就不显示  设置不可点击
            if (lists_price.size() >= 1) {

                findViewById(R.id.choose_goods_price_nsgv_ll).setVisibility(View.VISIBLE);
                findViewById(R.id.choose_goods_bottom_rl).setVisibility(View.VISIBLE);

                choose_goods_submit_tv.setClickable(true);

            } else {

                findViewById(R.id.choose_goods_price_nsgv_ll).setVisibility(View.GONE);
                findViewById(R.id.choose_goods_bottom_rl).setVisibility(View.GONE);

                choose_goods_submit_tv.setClickable(false);
            }

            chooseGoodsPriceGridAdapter.initCheckFalse(lists_price, 0);
            priceSelectPosition = 0;
            chooseGoodsPriceGridAdapter.notifyDataSetChanged();

//            if(BaseApplication.BasePreferences.readIsFavourable().equals("2")){
//
//                BigDecimal money = new BigDecimal(lists_price.get(0).money);
//                BigDecimal discount = new BigDecimal(chooseGoodsList.discount);
//                BigDecimal result = money.multiply(discount);
//
//                choose_goods_all_price_tv.setText(new DecimalFormat("#.00").format(result));
//
//                choose_goods_bottom_all_price_tv.setText("￥" + new DecimalFormat("#.00").format(result));
//
//            }else{
//
//                choose_goods_all_price_tv.setText(lists_price.get(0).money);
//
//                choose_goods_bottom_all_price_tv.setText("￥" + lists_price.get(0).money);
//
//            }

            choose_goods_all_price_tv.setText(getString(R.string.money_icon_text) + lists_price.get(0).money);
            choose_goods_bottom_all_price_tv.setText(getString(R.string.money_icon_text) + lists_price.get(0).money);

            choose_goods_number_tv.setText("1");

            choose_goods_all_price_number_tv.setText("（1张）");

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            Toast.makeText(ChooseGoodsActivity.this, toast, Toast.LENGTH_LONG).show();

        }

    });

    // 场次
    private ChooseGoodsNumListGet chooseGoodsNumListGet = new ChooseGoodsNumListGet(new AsyCallBack<ChooseGoodsNumListGet.ChooseGoodsNumListEntity>() {

        @Override
        public void onSuccess(String toast, int type, ChooseGoodsNumListGet.ChooseGoodsNumListEntity chooseGoodsNumListEntity) throws Exception {
            super.onSuccess(toast, type, chooseGoodsNumListEntity);

            lists_num.addAll(chooseGoodsNumListEntity.NubEntityList);

            chooseGoodsNumGridAdapter.initCheckFalse(lists_num, 0);
            numSelectPosition = 0;
            chooseGoodsNumGridAdapter.notifyDataSetChanged();

            if (!getIntent().getExtras().getString("is_seat").equals("1")&&!getIntent().getExtras().getString("status").equals("1")) {

                chooseGoodsPriceListGet.id = chooseGoodsNumListEntity.NubEntityList.get(0).id;
                chooseGoodsPriceListGet.execute(ChooseGoodsActivity.this);

            } else {

                if (lists_num.size() >= 1) {

                    choose_goods_submit_tv.setClickable(true);

                } else {

                    choose_goods_submit_tv.setClickable(false);

                }
            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            super.onFail(toast, type);

            Toast.makeText(ChooseGoodsActivity.this, toast, Toast.LENGTH_LONG).show();

            choose_goods_submit_tv.setClickable(false);

        }

    });

    //时间
    private ChooseGoodsListGet chooseGoodsListGet = new ChooseGoodsListGet(new AsyCallBack<ChooseGoodsListGet.ChooseGoodsListEntity>() {

        @Override
        public void onSuccess(String toast, int type, ChooseGoodsListGet.ChooseGoodsListEntity chooseGoodsListEntity) throws Exception {

            chooseGoodsList = chooseGoodsListEntity;

            lists_time.addAll(chooseGoodsListEntity.TimeEntityList);

            chooseGoodsTimeGridAdapter.initCheckFalse(lists_time, 0);
            timeSelectPosition = 0;
            chooseGoodsTimeGridAdapter.notifyDataSetChanged();

            chooseGoodsNumListGet.id = chooseGoodsListEntity.TimeEntityList.get(0).id;
            chooseGoodsNumListGet.execute(ChooseGoodsActivity.this);

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            Toast.makeText(ChooseGoodsActivity.this, toast, Toast.LENGTH_LONG).show();

            choose_goods_submit_tv.setClickable(false);

        }

    });

    private GoodsBookGet goodsBookGet = new GoodsBookGet(new AsyCallBack<String>(){

        @Override
        public void onSuccess(String toast, int type, String s) throws Exception {
            super.onSuccess(toast, type, s);

            Toast.makeText(ChooseGoodsActivity.this, toast, Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            super.onFail(toast, type);

            Toast.makeText(ChooseGoodsActivity.this, toast, Toast.LENGTH_LONG).show();

        }
    });

    private int goodsCount = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_choose_goods);

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        width = metric.widthPixels;  // 屏幕宽度（像素）

        setBackTrue();

        setTitleName(getResources().getString(R.string.choose_goods_title_text));

        choose_goods_submit_tv.setClickable(false);

        if(getIntent().getExtras().getString("status", "").equals("1")){

            choose_goods_submit_tv.setText(getResources().getString(R.string.goods_info_register_title_text));

        }else{

            if (getIntent().getExtras().getString("is_seat", "").equals("1")) {

                choose_goods_submit_tv.setText(getResources().getString(R.string.goods_info_bottom_seat_buy_text));

            } else {

                choose_goods_submit_tv.setText("立即购买");

            }

        }

        choose_goods_time_nsgv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(56));
        choose_goods_time_nsgv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(30));

        choose_goods_num_nsgv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));
        choose_goods_num_nsgv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));

        choose_goods_price_nsgv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));
        choose_goods_price_nsgv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));

        chooseGoodsTimeGridAdapter = new ChooseGoodsTimeGridAdapter(this, lists_time);
        chooseGoodsNumGridAdapter = new ChooseGoodsNumGridAdapter(this, lists_num);
        chooseGoodsPriceGridAdapter = new ChooseGoodsPriceGridAdapter(this, lists_price);

        choose_goods_time_nsgv.setAdapter(chooseGoodsTimeGridAdapter);
        choose_goods_num_nsgv.setAdapter(chooseGoodsNumGridAdapter);
        choose_goods_price_nsgv.setAdapter(chooseGoodsPriceGridAdapter);





        choose_goods_time_nsgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (!chooseGoodsTimeGridAdapter.isChecked.get(position)) {

                    chooseGoodsTimeGridAdapter.initCheckFalse(lists_time, position);
                    timeSelectPosition = position;
                    chooseGoodsTimeGridAdapter.notifyDataSetChanged();

                    lists_num.clear();
                    lists_price.clear();

                    chooseGoodsNumListGet.id = chooseGoodsList.TimeEntityList.get(position).id;
                    chooseGoodsNumListGet.execute(ChooseGoodsActivity.this);

                    goodsCount = 1;

                }
            }
        });

        choose_goods_num_nsgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (!chooseGoodsNumGridAdapter.isChecked.get(position)) {

                    chooseGoodsNumGridAdapter.initCheckFalse(lists_num, position);
                    numSelectPosition = position;
                    chooseGoodsNumGridAdapter.notifyDataSetChanged();

                    if (!getIntent().getExtras().getString("is_seat", "").equals("1")&&!getIntent().getExtras().getString("status", "").equals("1")) {

                        lists_price.clear();
                        chooseGoodsPriceListGet.id = lists_num.get(position).id;
                        chooseGoodsPriceListGet.execute(ChooseGoodsActivity.this);

                        goodsCount = 1;

                    }

                }

            }
        });

        choose_goods_price_nsgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (!chooseGoodsPriceGridAdapter.isChecked.get(position)) {

//                    Log.e("----------->", "priceSelectPosition" + priceSelectPosition + "position " + position);

                    chooseGoodsPriceGridAdapter.initCheckFalse(lists_price, position);
                    priceSelectPosition = position;
                    chooseGoodsPriceGridAdapter.notifyDataSetChanged();

//                    if(BaseApplication.BasePreferences.readIsFavourable().equals("2")){
//
//                        BigDecimal money = new BigDecimal(lists_price.get(position).money);
//                        BigDecimal discount = new BigDecimal(chooseGoodsList.discount);
//                        BigDecimal result = money.multiply(discount);
//
//                        choose_goods_all_price_tv.setText(new DecimalFormat("#.00").format(result));
//
//                        choose_goods_bottom_all_price_tv.setText("￥" + new DecimalFormat("#.00").format(result));
//
//                    }else{
//
//                        choose_goods_all_price_tv.setText(lists_price.get(position).money);
//
//                        choose_goods_bottom_all_price_tv.setText("￥" + lists_price.get(position).money);
//
//                    }

                    choose_goods_all_price_tv.setText(getString(R.string.money_icon_text) + lists_price.get(position).money);

                    choose_goods_bottom_all_price_tv.setText(getString(R.string.money_icon_text) + lists_price.get(position).money);

                    choose_goods_number_tv.setText("1");
                    choose_goods_all_price_number_tv.setText("（1张）");

                }

            }
        });

        choose_goods_submit_tv.setOnClickListener(this);
        choose_goods_add_ll.setOnClickListener(this);
        choose_goods_minus_ll.setOnClickListener(this);

        chooseGoodsListGet.id = getIntent().getExtras().getString("goodsInfoId");
        chooseGoodsListGet.group_id = BaseApplication.BasePreferences.readIsFavourable();
        chooseGoodsListGet.execute(ChooseGoodsActivity.this);





    }

    @Override
    public void onClick(View view) {

        BigDecimal old_price;
        BigDecimal price = null;
        BigDecimal result;

        DecimalFormat decimalFormat;

        switch (view.getId()) {

            case R.id.choose_goods_submit_tv:

                if (!getIntent().getExtras().getString("is_seat", "").equals("1") && !(goodsCount < Integer.parseInt(lists_price.get(priceSelectPosition).number))) {

                    MyToast.show(context, getString(R.string.choose_goods_limit_count_text), 2000);

                    return;
                }

                final Bundle bundle = getIntent().getExtras();

                bundle.putString("date", lists_time.get(timeSelectPosition).data);
                bundle.putString("hour", lists_time.get(timeSelectPosition).hour);
                bundle.putString("week", lists_time.get(timeSelectPosition).week);
                bundle.putString("discount", chooseGoodsList.discount);
                bundle.putString("performance_time", lists_time.get(timeSelectPosition).performance_time);
                bundle.putString("is_balance", lists_time.get(timeSelectPosition).is_balance);

                bundle.putString("season_time", lists_num.get(numSelectPosition).title + getResources().getString(R.string.space) + lists_num.get(numSelectPosition).times);

                if(bundle.getString("status", "").equals("1")){

                        new RegisterDialog(ChooseGoodsActivity.this, width, getIntent().getExtras().getString("title", "")) {
                            @Override
                            protected void onSubmit(String phone) {

                                JSONObject jsonObject = new JSONObject();

                                try {

                                    jsonObject.put("user_id", BaseApplication.BasePreferences.readUserId());
                                    jsonObject.put("show_id", bundle.getString("goodsInfoId", ""));
                                    jsonObject.put("season_id", lists_num.get(numSelectPosition).id);
                                    jsonObject.put("title", bundle.getString("title", ""));
                                    jsonObject.put("screenings", lists_time.get(timeSelectPosition).data + getResources().getString(R.string.space) + lists_num.get(numSelectPosition).times);
                                    jsonObject.put("picurl", bundle.getString("picurl", ""));
                                    jsonObject.put("phone", phone);
                                    jsonObject.put("status", bundle.getString("status", ""));


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                goodsBookGet.order = jsonObject.toString();

                                goodsBookGet.execute(ChooseGoodsActivity.this);

                            }
                        }.show();

                }else{

                    if (getIntent().getExtras().getString("is_seat", "").equals("1")) {

                        bundle.putString("title", bundle.getString("title", ""));
                        bundle.putString("url", Conn.SERVICE + Conn.TRILATERAL_LOGIN + "?productId=" + lists_num.get(numSelectPosition).product_id + "&user_id=" + BaseApplication.BasePreferences.readUserId());
                        bundle.putBoolean("isGoods", true);
                        bundle.putString("play_id", lists_num.get(numSelectPosition).id);

                        startActivity(new Intent(ChooseGoodsActivity.this, WebActivity.class).putExtras(bundle));

                    } else {

                        bundle.putString("money", lists_price.get(priceSelectPosition).money);
                        bundle.putString("goodsCount", goodsCount + "");
                        bundle.putString("total_price", choose_goods_bottom_all_price_tv.getText().toString().substring(1, choose_goods_bottom_all_price_tv.getText().toString().length()));
                        bundle.putString("play_id", lists_price.get(priceSelectPosition).id);

                        startActivity(new Intent(ChooseGoodsActivity.this, SubmitOrderActivity.class).putExtras(bundle));

                    }

                }

                break;

            case R.id.choose_goods_add_ll:

                if (goodsCount < Integer.parseInt(lists_price.get(priceSelectPosition).number)) {

                    goodsCount = Integer.parseInt(choose_goods_number_tv.getText().toString()) + 1;

                    old_price = new BigDecimal(choose_goods_bottom_all_price_tv.getText().toString().substring(1, choose_goods_bottom_all_price_tv.getText().toString().length()));

//                    if(BaseApplication.BasePreferences.readIsFavourable().equals("2")){
//
//                        BigDecimal item_price = new BigDecimal(lists_price.get(priceSelectPosition).money);
//                        BigDecimal discount = new BigDecimal(chooseGoodsList.discount);
//                        BigDecimal result_discount = item_price.multiply(discount);
//
//                        price = new BigDecimal(result_discount.toString());
//
//                    }else{
//
//                        price = new BigDecimal(lists_price.get(priceSelectPosition).money);
//
//                    }

                    price = new BigDecimal(lists_price.get(priceSelectPosition).money);
                    result = old_price.add(price);
//                    decimalFormat = new DecimalFormat("#.00");

//                    choose_goods_all_price_tv.setText(getString(R.string.money_icon_text) + decimalFormat.format(result));
                    choose_goods_number_tv.setText(goodsCount + "");
                    choose_goods_bottom_all_price_tv.setText(getString(R.string.money_icon_text) + result.setScale(0, BigDecimal.ROUND_HALF_UP).toString());
                    choose_goods_all_price_number_tv.setText(getString(R.string.submit_order_coupon_count_symbols_text) + goodsCount + getString(R.string.submit_order_coupon_count_text));

                } else {

                    MyToast.show(context, getString(R.string.choose_goods_limit_count_text), 2000);

                }

                break;

            case R.id.choose_goods_minus_ll:

                if (goodsCount - 1 >= 1) {

                    goodsCount = Integer.parseInt(choose_goods_number_tv.getText().toString()) - 1;

                    old_price = new BigDecimal(choose_goods_bottom_all_price_tv.getText().toString().substring(1, choose_goods_bottom_all_price_tv.getText().toString().length()));

//                    if(BaseApplication.BasePreferences.readIsFavourable().equals("2")){
//
//                        BigDecimal item_price = new BigDecimal(lists_price.get(priceSelectPosition).money);
//                        BigDecimal discount = new BigDecimal(chooseGoodsList.discount);
//                        BigDecimal result_discount = item_price.multiply(discount);
//
//                        price = new BigDecimal(result_discount.toString());
//
//                    }else{
//
//                        price = new BigDecimal(lists_price.get(priceSelectPosition).money);
//
//                    }

                    price = new BigDecimal(lists_price.get(priceSelectPosition).money);
                    result = old_price.subtract(price);
//                    decimalFormat = new DecimalFormat("#.00");

//                    choose_goods_all_price_tv.setText(getString(R.string.money_icon_text) + decimalFormat.format(result));
                    choose_goods_number_tv.setText(goodsCount + "");
                    choose_goods_bottom_all_price_tv.setText(getString(R.string.money_icon_text) + result.setScale(0, BigDecimal.ROUND_HALF_UP).toString());
                    choose_goods_all_price_number_tv.setText(getString(R.string.submit_order_coupon_count_symbols_text) + goodsCount + getString(R.string.submit_order_coupon_count_text));

                }

                break;

        }

    }
}
